import cv2
from pyzbar import pyzbar


class CodeScanner:
    def __init__(self):
        pass

    def scan_code(self, img):
        # 如果传递的路径,就读取路径下面的图片,否则传递的是图片,就直接读图片
        if isinstance(img,str):
            coder = cv2.imread(img)
        else:
            coder = img
        data = pyzbar.decode(coder)
        res =  data[0].data.decode('utf-8')
        # print(res)
        return res


    def showCamera(self):
        '''
            显示摄像头画面的demo
        '''
        # 调用摄像头(0,默认的第一个摄像头)
        cap = cv2.VideoCapture(0)
        while True:
            # 读取一帧画面,frame:三维矩阵
            ret,frame = cap.read()
            #显示当前帧
            cv2.imshow('扫码展示区', frame)
            # 等待键盘输入
            key = cv2.waitKey(10)
            # 当按下q键时关闭摄像头
            if key == ord('q'):
                break
        cv2.destroyAllWindows()

    def zh_cn(self, string):
        # 将中文重新编码后发给CV2显示,不过还是只能显示部分字符,问题未知.
        # 该方法慎用
        return string.encode('gb2312').decode(errors='ignore')

    def scan(self):
        cap = cv2.VideoCapture(0)
        while True:
            ret,frame = cap.read()
            # 此处的窗口名用英文,中文显示不正常
            cv2.imshow('Camera(press q to quit!)', frame)

            # 转换为灰度图
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

            #解析二维码
            text= None
            try:
                text = self.scan_code(frame)
            except Exception as e:
                pass

            if text:
                cap.release()
                cv2.destroyAllWindows()
                return text

            key = cv2.waitKey(100)
            if key == ord('q'):
                break
        cap.release()
        cv2.destroyAllWindows()

def main():
    pass
    scanner = CodeScanner()
    code = scanner.scan()
    print(code)

    
if __name__ == '__main__':
    main()